package com.yu.crm.service.impl;


import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yu.crm.constants.WxConstant;
import com.yu.crm.utils.AccessTokenTool;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author pan
 * @since 2020/9/25 15:25
 */
@Service
public class QrCreateService {

    public void createQrCode(String expireSeconds, String qrCodeId,String targetPath) throws IOException {
        //根据获取的access_token获取ticket
        String accessToken = AccessTokenTool.getAccessToken();
        String qrCreateUrl = WxConstant.WxRequestUrl.QR_CREATE_URL.replace("TOKEN",accessToken);
        //post请求获取ticket
//      {"expire_seconds": 604800, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": "test"}}}
        String body = HttpUtil.post(qrCreateUrl,
                "{\"expire_seconds\": "+ expireSeconds +"," +
                        " \"action_name\": \"QR_STR_SCENE\"," +
                        " \"action_info\": {\"scene\": {\"scene_str\": "+ qrCodeId +"}}}"
        );
        Map result = JSONUtil.toBean(body, Map.class);
        String ticket = (String)result.get("ticket");
        //根据ticket获取二维码
        String createQrCode = WxConstant.WxRequestUrl.CREATE_QR_CODE_URL.replace("TICKET", ticket);
        OutputStream out = null;
        try {
            HttpResponse response = HttpUtil.createGet(createQrCode).execute();
            byte[] bytes = response.bodyBytes();
            out = new FileOutputStream(targetPath);
            out.write(bytes);
            out.flush();
        } catch (IOException e) {
            if (null != out) {
                out.close();
            }
        }
    }
}
